package com.jingogo.security;

import com.jingogo.entity.User;
import com.jingogo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collections;

/**
 * 自定义用户详情服务
 * 
 * @author jingogo
 * @since 2024-01-01
 */
@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String userId) throws UsernameNotFoundException {
        try {
            Long id = Long.parseLong(userId);
            User user = userService.getUserById(id);
            
            if (user == null) {
                throw new UsernameNotFoundException("用户不存在");
            }

            if (user.getStatus() == 0) {
                throw new UsernameNotFoundException("用户已被禁用");
            }

            return new org.springframework.security.core.userdetails.User(
                user.getId().toString(),
                user.getPassword(),
                Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))
            );
        } catch (NumberFormatException e) {
            throw new UsernameNotFoundException("用户ID格式错误");
        }
    }
} 